<template>
  <div class="role">
    <div class="mb-20">
      <el-input v-model="roleIds" placeholder="roleId,1,2,3"></el-input>
    </div>

    <div class="mb-20 tree-contianer">
      <el-input class="w-400" placeholder="输入关键字进行过滤" v-model="filterRole">
      </el-input>
      <div class="tree-box">
        <el-tree ref="roleTree" :data="roleTree" :props="roleProps" default-expand-all
          :filter-node-method="filterRoleNode" show-checkbox :check-strictly="true" @check-change="handleRoleCheck" node-key="id">
          <span slot-scope="{ node, data }">{{ data.id }}-{{ data.roleName }}</span>
        </el-tree>
      </div>
    </div>

    <div class="mb-20">
      <el-input v-model="menuIds" placeholder="menuId,1,2,100"></el-input>
    </div>

    <div class="mb-20 tree-contianer">
      <el-input class="w-400" placeholder="输入关键字进行过滤" v-model="filterMenu">
      </el-input>
      <div class="tree-box">
        <el-tree ref="menuTree" :data="menuTree" :props="menuProps" default-expand-all
          :filter-node-method="filterMenuNode" show-checkbox @check-change="handleMenuCheck" node-key="id">
          <span slot-scope="{ node, data }">{{ data.id }}-{{ data.name }}</span>
        </el-tree>
      </div>
    </div>

    <div>
      <el-button @click="add">为角色添加菜单权限</el-button>
      <el-button type="danger" @click="remove">为角色删减菜单权限</el-button>
    </div>

  </div>
</template>

<script>
import {
  getList as getRoleList,
  grant,
  getRole,
  remove,
} from "@/api/system/role";
import { getList as getMenuList } from "@/api/system/menu";
import { searchTree } from '@/util/util'
export default {
  data() {
    return {
      filterRole: '',
      filterMenu: '',
      roleTree: [],
      menuTree: [],
      roleIds: '',
      menuIds: '',
      roleProps: {
        children: 'children',
        label: 'roleName',
      },
      menuProps: {
        children: 'children',
        label: 'name',
      }
    };
  },
  watch: {
    filterRole(val) {
      this.$refs.roleTree.filter(val);
    },
    filterMenu(val) {
      this.$refs.menuTree.filter(val);
    },
  },
  methods: {
    filterRoleNode(value, data) {
      if (!value) return true;
      return data.roleName.indexOf(value) !== -1;
    },
    filterMenuNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    getRoleList() {
      getRoleList().then(res => {
        this.roleTree = res.data.data || []
      })
    },
    getMenuList() {
      getMenuList().then(res => {
        this.menuTree = res.data.data || []
      })
    },
    handleRoleCheck() {
      const checkedIds = this.$refs.roleTree.getCheckedKeys()
      console.log(checkedIds)
      this.roleIds = checkedIds.join(',')
    },
    handleMenuCheck() {
      const checkedIds = this.$refs.menuTree.getCheckedKeys()
      const halfCheckeds = this.$refs.menuTree.getHalfCheckedKeys()
      this.menuIds = checkedIds.concat(halfCheckeds).join(',')
    },
    async remove() {
      if (!this.roleIds || !this.menuIds) {
        return
      }
      const valid = await this.$confirm('确认为角色移除菜单？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
      if (valid) {
        const roleIdList = this.roleIds.split(',')
        const removeMenuIdList = this.menuIds.split(',')
        const roleRequestList = roleIdList.map(item => {
          return getRole(item)
        })
        const roleMenuIds = await Promise.all(roleRequestList).then(res => {
          return res.map(r => r.data.data)
        })
        const grantRequestList = roleIdList.map((id, index) => {
          const menuIds = roleMenuIds[index].filter($0 => !removeMenuIdList.includes($0))
          return grant(id, menuIds.join(','))
        })
        await Promise.all(grantRequestList).then(res => {
          return res.map(r => r.data.data)
        }).then(res => {
          this.$message({
            type: 'success',
            message: '移除成功'
          })
        }).catch(error => {
          this.$message({
            type: 'error',
            message: '移除失败'
          })
        })
      }
    },
    async add() {
      if (!this.roleIds || !this.menuIds) {
        return
      }
      const valid = await this.$confirm('确认为角色添加菜单？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
      if (valid) {
        const roleIdList = this.roleIds.split(',')
        const menuIdList = this.menuIds.split(',')
        const roleRequestList = roleIdList.map(item => {
          return getRole(item)
        })
        const roleMenuIds = await Promise.all(roleRequestList).then(res => {
          return res.map(r => r.data.data)
        })
        const grantRequestList = roleIdList.map((id, index) => {
          const menuIds = Array.from(new Set(menuIdList.concat(roleMenuIds[index])))
          return grant(id, menuIds.join(','))
        })
        await Promise.all(grantRequestList).then(res => {
          return res.map(r => r.data.data)
        }).then(res => {
          this.$message({
            type: 'success',
            message: '添加成功'
          })
        }).catch(error => {
          this.$message({
            type: 'error',
            message: '添加失败'
          })
        })
      }
    },
  },
  created() {
    this.getRoleList()
    this.getMenuList()
  }
};
</script>
<style lang="scss" scoped>
.role {
  .tree-contianer {
    width: 500px;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px;
  }

  .tree-box {
    max-height: 300px;
    overflow: auto;
  }
}
</style>